package org.example.domain.strategy.service.rule.tree.impl;

import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.model.valobj.RuleLogicCheckTypeVO;
import org.example.domain.strategy.model.valobj.StrategyAwardRuleModelVO;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.rule.tree.ILogicTreeNode;
import org.example.domain.strategy.service.rule.tree.factory.DefaultTreeFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author Fuzhengwei bugstack.cn @小傅哥
 * @description 次数锁节点
 * @create 2024-01-27 11:22
 */
@Slf4j
@Component("rule_lock")
public class RuleLockLogicTreeNode implements ILogicTreeNode {
    @Resource
    private IStrategyRepository repository;

    private Long userRaffleCount=1L;

    @Override
    public DefaultTreeFactory.TreeActionEntity logic(String userId, Long strategyId, Integer awardId,String ruleValue) {
        StrategyAwardRuleModelVO ruleModelVO=repository.queryStrategyRuleModelVO(strategyId, awardId);
        log.info("规则过滤-次数锁 userId:{} strategyId:{} ruleModel:{}",userId,strategyId,ruleModelVO.getRuleModels());
//        String ruleValue = repository.queryStrategyRuleValue(strategyId,awardId, ruleModelVO.getRuleModels());
        long raffleCount=0L;
        try{
            raffleCount = Long.parseLong(ruleValue);
        }catch (Exception e){
            throw new RuntimeException("规则过滤-次数 ruleValue:"+ruleValue+"配置不正确");
        }

        // 用户抽奖次数大于规则限定值，规则放行
        if (userRaffleCount>= raffleCount) {
            return DefaultTreeFactory.TreeActionEntity.builder()
                    .ruleLogicCheckType(RuleLogicCheckTypeVO.ALLOW)
                    .strategyAwardVO(new DefaultTreeFactory.StrategyAwardVO(awardId,ruleValue))
                    .build();
        }
        // 用户抽奖次数小于规则限定值，规则拦截
        return DefaultTreeFactory.TreeActionEntity.builder()
                .ruleLogicCheckType(RuleLogicCheckTypeVO.TAKE_OVER)
                .strategyAwardVO(new DefaultTreeFactory.StrategyAwardVO(awardId,ruleValue))
                .build();
    }
}
